

#include "BMPFileManager.h"


BMPFileManager::BMPFileManager(const char *inFilename):IFileManager(inFilename)
{

}

bool BMPFileManager::ConvertBGRtoRGB()
{
	const DWORD BitmapLength = mSizeX * mSizeY * 3;
	byte Temp;  // not quick but it works  
	for(DWORD i=0; i< BitmapLength; i += 3) 
	{
	    Temp = mBmpData[i];
	    mBmpData[i] = mBmpData[i+2];
	    mBmpData[i+2] = Temp;
	}
	return true;
}

bool BMPFileManager::Open()
{
	ZeroMemory(&mBMInfo,sizeof(BITMAPINFO));
	mGLDC = wglGetCurrentDC();
	if(mBmpData != NULL) mBmpData = NULL;

	mBMInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	mBMInfo.bmiHeader.biBitCount = 0;

	HANDLE DIBHandle = LoadImage(0,mFilename, IMAGE_BITMAP, 0, 0,LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_LOADFROMFILE); 
	GetDIBits(mGLDC, (HBITMAP)DIBHandle, 0,0, NULL, &mBMInfo, DIB_RGB_COLORS);

	mSizeX = mBMInfo.bmiHeader.biWidth;
	mSizeY = mBMInfo.bmiHeader.biHeight;				
	mBMInfo.bmiHeader.biBitCount = 24;				
	mBMInfo.bmiHeader.biCompression = BI_RGB;  
	const DWORD BitmapLength = mSizeX * mSizeY * 3;	
												
	mBmpData = new byte[BitmapLength];	

	if (GetDIBits(mGLDC, (HBITMAP)DIBHandle, 0, mSizeY, mBmpData, &mBMInfo, DIB_RGB_COLORS)) 
	{
		ConvertBGRtoRGB();							// NOTE: BMP is in BGR format but OpenGL needs RGB unless you use GL_BGR_EXT
		DeleteObject(DIBHandle);
		return true;
	}
	else 
	{	
		delete [] mBmpData;	
		return false;
	}
}

BMPFileManager::~BMPFileManager()
{
	if(mBmpData)
		delete [] mBmpData;
}